import { OrganizeSimpleTree } from "api/sys/organize";

export default {
  data() {
    return {
      treeLoading: false,
      orgTreeProps: {
        children: "childList",
        label: "name",
        isLeaf: "leaf",
      },
    };
  },
  methods: {
    /**
     * 获取部门数据
     */
    async _OrganizeSimpleTree({ parentId = 0, params = {} } = {}) {
      try {
        const data = await OrganizeSimpleTree(parentId, params);
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 加载部门数据
     */
    async loadNode(node, resolve, disabledType = false) {
      const { level, checked } = node;
      let data = [];
      if (level === 0) {
        this.treeLoading = true;
        this.node_had = node;
        const data = await this._OrganizeSimpleTree({
          parentId: this.parentId || 0,
          // 只是为了兼容业务，在personal/law/law-dialog组件中，第一级只想取到当前部门
          params: this.treeParams || {},
        });
        this.treeLoading = false;
        this.resolve_had = resolve;
        resolve(this.treeDataFormat({ data, disabledType }));
      } else {
        const {
          data: { id: organizeId },
        } = node;
        data = await this._OrganizeSimpleTree({
          parentId: organizeId,
          params: this.treeParams || {},
        });
        resolve(
          this.treeDataFormat({
            data,
            organizeId,
            disabledType,
            checked,
          })
        );
      }
    },
    /**
     * 树形数据格式化
     */
    treeDataFormat({ data, organizeId, disabledType, checked }) {
      let tempArr = [];
      data.map((item) => {
        const { subCount } = item;
        item.leaf = !subCount;
        item.disabled = disabledType;
        if (organizeId) {
          item.parentId = organizeId;
        } else {
          item.parentId = 0;
        }
        if (checked) {
          tempArr.push(item.id);
        }
      });
      if (tempArr.length) {
        this.$refs.tree.setCheckedKeys([...(this.allCheckedData || []), ...tempArr]);
      }
      return data;
    },
  },
};
